﻿Imports System.Reflection
Imports Microsoft.Xna.Framework

#If NETFX_CORE Then
#End If

Namespace Global.Runa.UI.Metadata

    Public Class ColorConverter
        Inherits TypeConverter

        Public Sub New(g As Game)
            MyBase.New(g)
        End Sub

        Public Overrides Function ConvertFromInvariantString(text As String) As Object       
            Dim typ = GetType(Color)
#If NETFX_CORE Then
            Dim ps = typ.GetRuntimeProperties()
            For Each p In ps
                If p.Name.ToLower() = text.ToLower() Then
                    Return p.GetValue(New Color())
                End If
            Next
#Else
            Dim ps = typ.GetProperties()
            For Each p In ps
                If p.Name.ToLower() = text.ToLower() Then
                    Return p.GetValue(New Color(), Nothing)
                End If
            Next
#End If
            Try
                Dim vc As New Vector4Converter(Me.Game)
                Dim result As Vector4 = vc.ConvertFromString(text)
                Return Color.FromNonPremultiplied(result)
            Catch ex As Exception
                Return Color.Transparent
            End Try
        End Function

        Public Overrides Function ConvertFromString(text As String) As Object
            Return ConvertFromInvariantString(text)
        End Function

        Public Overrides Function ConvertToInvariantString(value As Object) As String
            Dim typ = GetType(Color)
#If NETFX_CORE Then
            Dim ps = typ.GetRuntimeProperties()
            For Each p In ps
                Dim v = p.GetValue(New Color())
                If v Is value Then
                    Return p.Name
                End If
            Next
#Else
            Dim ps = typ.GetProperties()
            For Each p In ps
                Dim v = p.GetValue(New Color(), Nothing)
                If v Is value Then
                    Return p.Name
                End If
            Next
#End If
            Return ""
        End Function

        Public Overrides Function ConvertToString(value As Object) As String
            Return ConvertToInvariantString(value)
        End Function

    End Class

End Namespace